package com.youzikj.wx.core.controller;

import static org.apache.commons.lang.StringUtils.*;

import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.youzikj.wx.core.comm.Utils;
import com.youzikj.wx.core.service.CoreService;

@Controller
public class SysController {

	@Autowired
	private CoreService coreService;

	private Logger log = LoggerFactory.getLogger(SysController.class);

	/**
	 * 错误页面
	 * @param msg
	 * @return
	 */
	@RequestMapping("error_page")
	public String illegal(String msg, Model m) {
		if (isBlank(msg)) {
			m.addAttribute("msg", "非法参数");
		} else {
			m.addAttribute("msg", msg);
		}
		return "error";
	}

	/**
	 * 网关
	 * @param code
	 * @param r
	 * @return
	 */
	@RequestMapping("gateway")
	public String gateway(String code, HttpSession session, RedirectAttributes r) {
		
		if (isBlank(code)) {
			r.addFlashAttribute("msg", "请在微信公众号中访问");
			return "redirect:/error_page";
		}
		
		String openid = null;
		try {
			openid = Utils.getUserInfoByCode(code).getOpenId();
		} catch (Exception e) {
			log.error("获取openid失败", e);
			r.addFlashAttribute("msg", "系统错误");
			return "redirect:/error_page";
		}
		if (isBlank(openid)) {
			r.addFlashAttribute("msg", "系统错误");
			return "redirect:/error_page";
		}
		
		try {
			session.setAttribute("String", openid);
		} catch (Exception e) {
			log.error("获取openid失败", e);
			r.addFlashAttribute("msg", "系统错误");
			return "redirect:/error_page";
		}
		
		return "redirect:/task_list";
	}

	/**
	 * 添加任务
	 * @return
	 */
	@RequestMapping("task_to_pub")
	public String task_to_pub() {
		return "task_pub";
	}
	
	/**
	 * 任务列表
	 * @return
	 */
	@RequestMapping("task_list")
	public String task_list(Model m) {
		try {
			//TODO 需要支持分页
			m.addAttribute("list", coreService.all());
		} catch (Exception e) {
			log.error("查询任务列表失败", e);
			m.addAttribute("msg", "系统错误");
		}
		return "task_list";
	}

	/**
	 * 任务详情
	 * @return
	 */
	@RequestMapping("task_detail")
	public String task_detail(String taskId, Model m, RedirectAttributes r) {
		return "task_detail";
	}

	/**
	 * 用户列表
	 * @return
	 */
	@RequestMapping("task_user")
	public String task_user(String taskId, String subId, Model m, RedirectAttributes r) {
		return "task_user";
	}

	/**
	 * 任务规则
	 * @return
	 */
	@RequestMapping("task_rule")
	public String task_rule() {
		return "task_rule";
	}

}
